package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"mock/grpc_test/proto"
	"net"
)

type Server struct {}

func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {

	//业务逻辑
	return &proto.HelloReply{
		Message: "hello " + request.Name,
	}, nil
}

func main() {
	interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {

		md, ok := metadata.FromIncomingContext(ctx)
		if !ok {
			return resp, status.Error(codes.Unauthenticated, "无认证信息")
		}
		var appid, appkey string
		if val1, ok := md["appid"]; ok {
			appid = val1[0]
		}
		if val1, ok := md["appkey"]; ok {
			appkey = val1[0]
		}
		if appid != "101010" || appkey != "i am key" {
			return resp, status.Error(codes.Unauthenticated, "无认证信息")
		}
		i, err := handler(ctx, req)
		fmt.Println("请求完成")
		return i, err
	}
	option := grpc.UnaryInterceptor(interceptor)
	server := grpc.NewServer(option)
	proto.RegisterGreeterServer(server, &Server{})
	listen, err := net.Listen("tcp", "0.0.0.0:8888")
	if err != nil {
		panic("failed to listen :" + err.Error())
	}
	err = server.Serve(listen)
	if err != nil {
		panic("failed to start grpc:" + err.Error())
	}
}